using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading;
namespace sort
{
    internal class Timer
    {
        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceCounter(
            out long lpPerformanceCount);

        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceFrequency(
            out long lpFrequency);

        private long startTime, stopTime;
        private long freq;
        private bool iswin;
        private long Now {
            get 
            {
                long ret;
                if (iswin)
                {
                    if (QueryPerformanceCounter(out ret) == false)
                    {
                        // high-performance counter not supported
                        throw new Exception();
                    }
                }
                else
                {
                    ret= System.Environment.TickCount;
                }
                return ret;
            }
        }
        // Constructor
        public Timer()
        {
            startTime = 0;
            stopTime = 0;
            if (Environment.OSVersion.Platform == PlatformID.Unix) iswin = false;
            else iswin = true;
            if (iswin)
            {
                if (QueryPerformanceFrequency(out freq) == false)
                {
                    // high-performance counter not supported
                    throw new Exception();
                }
            }
            else
            {
                freq = 1;
            }
        }



        // Start the timer
        public void Start()
        {
            // lets do the waiting threads there work
            Thread.Sleep(0);

            startTime = Now;
        }

        // Stop the timer
        public void Stop()
        {
            stopTime = Now;
        }

        // Returns the duration of the timer (in seconds)
        public double Duration
        {
            get
            {
                return (double)(stopTime - startTime) / (double)freq;
            }
        }
    }
}
